let data = [
    {
        id: 1,
        username: '阿尼亚',
        avatar: '',
        text: '吃瓜超能力',
        children: [
            {
                username: '佛杰',
                avatar: '',
                text: '在想什么',
                receiveId: 1,
                toName: '阿尼亚',
                isInReceive: false
            },

            {
                username: '约尔',
                avatar: '',
                text: '听话听话',
                receiveId: 1,
                toName: '阿尼亚',
                isInReceive: false
            },

            {
                username: '店长',
                avatar: '',
                text: '记得付钱',
                receiveId: 1,
                toName: '佛杰',
                isInReceive: true
            },

            {
                username: '店长',
                avatar: '',
                text: '记得付钱',
                receiveId: 1,
                toName: '佛杰',
                isInReceive: true
            },

            {
                username: '店长',
                avatar: '',
                text: '记得付钱',
                receiveId: 1,
                toName: '佛杰',
                isInReceive: true
            }
        ]
    },
    {
        id: 2,
        username: '张三',
        avatar: '',
        text: '你好',
        children: [
            {
                username: '佛杰',
                avatar: '',
                text: '你好',
                receiveId: 2,
                toName: '张三',
                isInReceive: false
            },

            {
                username: '约尔',
                avatar: '',
                text: '你好',
                receiveId: 2,
                toName: '张三',
                isInReceive: false
            },

            {
                username: '店长',
                avatar: '',
                text: '呼呼',
                receiveId: 2,
                toName: '佛杰',
                isInReceive: true
            }
        ]
    },
    {
        id: 3,
        username: '店长',
        avatar: '',
        text: 'O(∩_∩)O哈哈~',
        children: [
            {
                username: '佛杰',
                avatar: '',
                text: '额',
                receiveId: 3,
                toName: '店长',
                isInReceive: false
            },

            {
                username: '约尔',
                avatar: '',
                text: '嗯',
                receiveId: 3,
                toName: '佛杰',
                isInReceive: true
            }
        ]
    }
]

let dataLength = data.length;

let list = document.getElementById('list');
let textarea = document.getElementById('text');

let insert = insertTo();


// 信息对象

const recData = {
    avatar: '',
    username: '欧文',
    text: '',
}

let newRecData = recData;

function huifu(e) {
    e.stopPropagation();

    const [f, s] = e.currentTarget.dataset.index.split(',').map(v => parseInt(v));
    newRecData = {
        ...recData,
        toName: data[f].children[s].username,
        receiveId: f + 1,
        isInReceive: true
    }
    insert = insertTo(f, s)
    textarea.setAttribute('placeholder', `回复@${data[f].children[s].username}`)
    textarea.value = ''
}

function dropDown(e) {

    e.stopPropagation()
    let secondList = e.target.previousElementSibling;
    if (e.target.dataset.dropdown == 1) {
        secondList.className = 'second_list down'
        e.target.setAttribute('data-dropdown', 0)
    }
    else {
        secondList.className = 'second_list up'
        e.target.setAttribute('data-dropdown', 1)
    }
}

// 插入数据函数

function insertTo(f, s) {
    return function () {
        if (f >= 0) {
            data[f].children.push(newRecData)
            // console.log(newRecData)
        }
        else {
            newRecData = {
                ...newRecData,
                id: dataLength + 1,
                children: []
            }
            // console.log(newRecData)
            data.push(newRecData)
        }
    }
}

function render() {

    list.innerHTML = ''

    data.forEach(firstItem => {
        // 创建dom结构
        let firstReveDom = document.createElement('div');
        firstReveDom.setAttribute('data-recId', firstItem.id);
        firstReveDom.setAttribute('data-index', firstItem.id - 1);
        firstReveDom.className = 'first_item'
        firstReveDom.innerHTML = `
                <div class = 'userinfo'>
                    <img src="./avatar.jpg">
                    <div>${firstItem.username}</div>
                </div>
                <div class='text_cont'>
                    <div class = 'text'>${firstItem.text}</div>
                    ${firstItem.children.length ? `<div class = 'second_list up' id='secondList'>${firstItem.children.map((secondItem, index) => {
            return `
                            <div class = 'second_item' onclick='huifu(event)' data-index='${firstItem.id - 1},${index}'>
                                ${secondItem.isInReceive ? `${secondItem.username} <span> 回复 @</span> ${secondItem.toName}` : secondItem.username}:
                                <span>${secondItem.text}</span>
                            </div>
                        `
        }).join(' ')}</div>` : ''}
                    ${(firstItem.children.length > 3) ? `<div class = 'more' onclick='dropDown(event)' data-dropdown='1' >共${firstItem.children.length}条回复</div>` : ''}
                </div>
        `

        // 添加事件
        firstReveDom.addEventListener('click', function (e) {
            const index = parseInt(e.currentTarget.dataset.index);
            // console.log(index, e, e.currentTarget.dataset)
            newRecData = {
                ...recData,
                toName: data[index].username,
                isInReceive: false,
                receiveId: index + 1
            }
            insert = insertTo(index)
            textarea.setAttribute('placeholder', `回复@${data[index].username}`)
            textarea.value = ''
        })

        list.appendChild(firstReveDom);



    });
}

function sent() {

    newRecData = {
        ...newRecData,
        text: textarea.value
    }

    textarea.value = ''
    textarea.setAttribute('placeholder', '点击发送评论吧')

    insert()

    render()

    putIndexDB()
}

function quxiao() {
    newRecData = recData;

    textarea.value = ''
    textarea.setAttribute('placeholder', '点击发送评论吧')
}

// 变更数据库
function putIndexDB() {
    let db;
    let request = window.indexedDB.open('pinlun', 2);
    request.onsuccess = function (e) {
        db = e.target.result;
        console.log('chenggo')

        let req = db.transaction(['pinlun'], 'readwrite')
            .objectStore('pinlun')
            .put({ pinlunList: JSON.stringify(data), id: 1 });
        req.onsuccess = e => {
            console.log('成功')
        }

    }
}

window.addEventListener('load', function () {


    let db;
    let request = window.indexedDB.open('pinlun', 2);
    request.onsuccess = function (e) {
        db = e.target.result;
        console.log('chenggo')
        if (db.objectStoreNames.contains('pinlun')) {
            let transaction = db.transaction(['pinlun']);
            let objectStore = transaction.objectStore('pinlun');
            let req = objectStore.get(1);
            req.onerror = e => {
                console.log('失败')
            }
            req.onsuccess = e => {
                // console.log(req.result, e, '')
                data = JSON.parse(req.result.pinlunList) || data;
                render()
            }
        }
        else {
            render()
        }

    }

})

window.addEventListener('unload', function () {
    let db;
    let request = window.indexedDB.open('pinlun', 2);
    request.onsuccess = function (e) {
        db = e.target.result;
        console.log('chenggo')

        let req = db.transaction(['pinlun'], 'readwrite')
            .objectStore('pinlun')
            .put({ pinlunList: JSON.stringify(data), id: 1 });
        req.onsuccess = e => {
            console.log('成功')
        }

    }
    request.onupgradeneeded = function (event) {
        console.log('升级')
        db = event.target.result;
        if (!db.objectStoreNames.contains('pinlun')) {
            let objectStore = db.createObjectStore('pinlun', { keyPath: 'id' });
            objectStore.createIndex('pinlunList', 'pinlunList', { unique: false });
            objectStore.createIndex('id', 'id', { unique: true });
            objectStore.add({ pinlunList: JSON.stringify(data), id: 1 })
        }
        else {
            let req = db.transaction(['pinlun'], 'readwrite')
                .objectStore('pinlun')
                .add({ pinlunList: JSON.stringify(data), id: 1 });
            req.onsuccess = e => {
                console.log('成功')
            }
        }
    }
});

// ;
// (function () {
//     let db;
//     let request = window.indexedDB.open('pinlun', 2);
//     request.onsuccess = function (e) {
//         db = e.target.result;
//         console.log('chenggo---')

//         data.push({...newRecData,text:'和红烧豆腐'})

//         let req = db.transaction(['pinlun'], 'readwrite')
//                 .objectStore('pinlun')
//                 .put({ pinlunList: JSON.stringify(data), id: 1 });
//             req.onsuccess = e => {
//                 console.log('成功---')
//             }
//             req.onerror = e =>{
//                 console.log('失败' ,e)
//             }
//     }
//     request.onupgradeneeded = function (event) {
//         console.log('升级','---')
//         db = event.target.result;
//         if (!db.objectStoreNames.contains('pinlun')) {
//             let objectStore = db.createObjectStore('pinlun', { keyPath: 'id' });
//             objectStore.createIndex('pinlunList', 'pinlunList', { unique: false });
//             objectStore.createIndex('id', 'id', { unique: true });
//             objectStore.add({ pinlunList: JSON.stringify(data), id: 1 })
//         }
//         else {
//             console.log(3)
//             let req = db.transaction(['pinlun'], 'readwrite')
//                 .objectStore('pinlun')
//                 .put({ pinlunList: JSON.stringify(data), id: 1 });
//             req.onsuccess = e => {
//                 console.log('成功')
//             }
//         }
//     }
//     request.onerror=()=>{
//         console.log('错误')
//     }
// })()